﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Wechat.API.Filter;
using Wechat.API.Models;
using Wechat.Util.Auth;
using Wechat.Util.Encryp;
using Wechat.Util.ModelStates;
using Wechat.Util.Request;
using Wechat.Util.ReturnMessage;
using Wechat.Util.StateCode;

namespace Wechat.API.Controllers
{
    [RoutePrefix("api/logon"), AntiXssSqlInject]
    [UnUserAuthorizeAttribute]//非用户授权//  其实可以不用这个
    public class LogOnController : ApiController
    {
        [Route("onauth"), HttpPost]
        public ResultMessage OnAuth(OnAuthRequset requset)
        {
            ResultMessage result = new ResultMessage();
            result.Status = false;
            result.Code = (int)EnumApiStateCode.ParameterMissing;
            result.Message = "授权失败，请求参数不为空！";

            if (requset != null)
            {
                if (ModelState.IsValid)
                {
                    //获取用户信息进行登录
                    var operInfo = new OperaterInfo()
                    {
                        LoginName = "admin",
                        Pwd = "gOWWV2PClQF1m9dn7lO7fQ==",
                        OptId = 1
                    };
                    if (operInfo != null)
                    {
                        //比对密码是否一致
                        if (!EncryptUtil.GetByKey(requset.pwd, operInfo.OptId.ToString()).Equals(operInfo.Pwd))
                        {
                            string pwd = EncryptUtil.PutBykey(operInfo.Pwd, operInfo.OptId.ToString());
                            result.Message = "授权失败，密码错误！";
                        }
                        else
                        {
                            result.Status = true;
                            result.Code = (int)EnumApiStateCode.Success;
                            requset.pwd = operInfo.Pwd;
                            result.Data = UserAuth.GetAuthString(requset);
                            result.Message = "授权成功！";
                        }
                    }
                    else
                    {
                        result.Code = (int)EnumApiStateCode.ParameterInvalid;
                        result.Message = "授权失败，登录名用户不存在！";
                    }
                }
                else
                {
                    result.Code = (int)EnumApiStateCode.ParameterValidationFailed;
                    result.Message = "授权失败，参数校验失败！";
                }
            }

            return result;
        }
    }
}
